package net.rayherring;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Logger;

import net.milkbowl.vault.permission.Permission;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;

public class OnlinePlayersSQL extends JavaPlugin {
	
	Logger log = Logger.getLogger("Minecraft");
	public final OnlinePlayersSQLConfig opConfig = new OnlinePlayersSQLConfig(this);
	public final OnlinePlayersSQLLib opSql = new OnlinePlayersSQLLib(this);
	public Permission permission = null;
	private ResultSet result;
	
	/* private Player players[]; */
		
	public void onEnable() {
		PluginDescriptionFile pdf = getDescription();

		opConfig.loadConfiguration();
		log.info("[" + pdf.getName() + "] " + pdf.getVersion() + " enabled.");
	
		new MyOnlPlayerListener(this);
		
		opSql.openConnection();
		
		try {
			opSql.updateTableSchema();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			 e.printStackTrace();
		}
		
		if ( opSql.tableExists(this.opConfig.getMySQLTable()) ) {
			opSql.SqlQuery("UPDATE " + this.opConfig.getMySQLTable() + " SET online = false");
		}
		
		setupPermissions();
	}
	
	private boolean setupPermissions() {
		RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
		
		if ( permissionProvider != null ) {
			permission = permissionProvider.getProvider();
		}
		return ( permission != null );		
	}

	public void onDisable() {
		PluginDescriptionFile pdf = getDescription();
		log.info(pdf.getName() + " " + pdf.getVersion() + " disabled.");
		
		opSql.SqlQuery("UPDATE " + this.opConfig.getMySQLTable() + " SET online = false");
		
		opSql.closeConnection();
	}
	
	public void updatePlayerRecord(Player player) {
		String primaryGroup = null;
		Player thisPlayer = player.getPlayer();
		String playerName = thisPlayer.getName();
		String playerWorld = thisPlayer.getWorld().getName();
		String ipAddress = thisPlayer.getAddress().getAddress().getHostAddress();
		String sqlTable = this.opConfig.getMySQLTable();
		int logonTime = (int) (System.currentTimeMillis()/1000);
		int logonTime2 = (int) thisPlayer.getPlayerTime();
		
		result = this.opSql.SqlQuery("SELECT * FROM " + sqlTable + " WHERE player='" + playerName + "'");
			
		if ( this.opConfig.isShowDebug()) {
			log.info("Player: " + playerName + " Logon Time: " + logonTime2);
		}
		
		try {
			if ( result.isBeforeFirst() ) {
				this.opSql.SqlQuery("UPDATE " + sqlTable + 
						" SET online = true, " +
						" current_world = '" + playerWorld + "', " + 
						" ip_address = '" + ipAddress + "', " +
						" logon_time = " + logonTime + 
						" WHERE player='" + playerName + "'");
			} else {
				this.opSql.SqlQuery("INSERT INTO " + sqlTable + " (player,current_world,ip_address,logon_time,online) " +
						"VALUES ('" + playerName + "', '" + playerWorld + "', " +
								"'" + ipAddress + "', " + logonTime + ", 1);");
			}
		} catch (SQLException e) {
			
		}
		
		if ( this.permission != null ) {
			primaryGroup = this.permission.getPrimaryGroup(player.getPlayer().getWorld().getName(), player.getPlayer().getName());
			
			this.opSql.SqlQuery("UPDATE " + this.opConfig.getMySQLTable() + " SET " +
					"permission_group='" + primaryGroup + "' " +
					"WHERE player='" + player.getPlayer().getName() + "';" );
		}
	}
	
	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
		@SuppressWarnings("unused")
		Player player = null;

		if ( sender instanceof Player) {
			player = (Player) sender;
			
			if ( args.length == 0 ) {
				return false;
			}
			
			if ( command.getName().equalsIgnoreCase("onl")) {
				if ( args[0].equalsIgnoreCase("resync") ) {
					this.opSql.SqlQuery("UPDATE " + this.opConfig.getMySQLTable() + " SET online = FALSE;");

					Player[] players = this.getServer().getOnlinePlayers();
				
					for ( int i = 0; i < players.length ; i++ ) {
						this.updatePlayerRecord(players[i]);
					}
					return true;
				} else {
					sender.sendMessage("Invalid /onl option. Valid options: resync");
				}
			} else { 
				sender.sendMessage("Invalid /onl option! Valid options: resync");
			}
		}
		
		return false;
	}
}
